<template>
  <div class="container" :class="[{'wm-container':isWm,'yht-container':isYht}]">
    <!-- 定位 -- 搜索 -- 分类 -->
    <div class="tab-search ptb10" :class="[{'wm-tabBgimg':isWm,'yht-tabBgimg':isYht}]">
      <div class="top df df-c">
      <div class="address df" @click="replaceAddress">
        <img class="img" src="../assets/images/common/positioning_white.png">
        <span class="cFFF plr5">{{addrName}}</span>
        <div class="right-arrow"></div>
      </div>
      <div class="search df1" @click="openWebView('/search/home', 'h5')">
        <img src="../assets/images/common/search.png" alt="">
        <input type="text" placeholder="输入药品名称、药品编码" disabled>
      </div>
      <div class="vip-code df" @click="openWebView('/classify/home', 'h5')">
        <div class="cFFF mr5">分类</div>
        <img class="img" src="../assets/images/home/classify.png">
      </div>
      </div>
    </div>
    <div class="main" v-if="showMain">
      <!--我的服务-->
      <div class="group service-group">
        <!-- <div class="group-title">我的服务</div> -->
         <!-- todo 目前所有模块暂定为跳转商城h5页面 -->
        <div class="nav-wrap">
          <div
            class="nav-item "
            v-for="(item, index) in myService"
            :key="index"
            @click="jumpWebView(item.href)"
          >
            <img :src="item.icon">
            <div class="fs12">{{item.name}}</div>
          </div>
        </div>
      </div>

      <!-- 限时抢购 -->
      <div class="group activityModule df-col" v-if="flashSale || (activityModule && activityModule.length)">
        <div class="df df-sb" v-if="flashSale">
          <div class="df df-c">
            <div class="group-title">限时抢购</div>
            <div class="df title-time">
              <span class="field cFFF df-c">{{currentTime}}点场</span>
              <span class="time df-c">{{hours || '00'}}:{{minutes || '00'}}:{{seconds || '00'}}</span>
            </div>
          </div>
          <div class="more cF9454E right-arrow_ig df1 fs13" @click="openWebView('/activity/secKill', 'h5')">优质好物轮番秒杀</div>
        </div>
        <!-- 秒杀商品 -->
        <div class="seckill" v-if="flashSale">
          <scroll-bar :scrollHeight="130">
            <div class="seckill-scroll-item" v-for="(item,index) in secKillList" :key="index" @click="openWebView(`/goods/detail?chainId=0&id=${item.id}`, 'h5')">
              <div class="seckill-img br4"><img :src="item.picUrl" />
                <!-- <img class="rx_img" v-if="item.rx" src="../../assets/images/default/rx_list.png" alt=""> -->
              </div>
              <div class="seckill-scale br8 mt5">
                <div class="scale-line br8 cFFF" :style="{width:item.scale}"></div>
              </div>
              <div class="dot fs11 seckill-productName">{{item.productName}}</div>
              <p class="fs13 cF9454E dot lh18 mt5">
                <span class="fs11">￥{{item.activityPriceYuan || '00.00'}}</span>
                <span class="tx-dt c999 dot fs8 seckill-price">￥{{item.priceYuan || '00.00'}}</span>
              </p>
            </div>
          </scroll-bar>
        </div>
        <!--activity-->
        <div class="activity">
          <div class="activity-item" v-for="(item, index) in activityModule" :key="index" @click="openWebView(item.goUrl, 'h5')">
            <img class="w100p h100p" :src="item.imgSrc" alt />
          </div>
        </div>
      </div>

      <!-- 健康管家 -->
      <div class="group health-group" v-if="false">
        <div class="group-title">健康管家</div>
        <ul class="df-row">
          <li @click="openWebView('/index', 'healthWX')">
            <img src="../assets/images/home/health_community.png" alt="">
          </li>
          <li @click="openWebView('/chronic', 'healthWX')">
            <img src="../assets/images/home/health_chronic_disease.png" alt="">
          </li>
          <li @click="openWebView('/my/memberList', 'healthWX')">
            <img src="../assets/images/home/health_file.png" alt="">
          </li>
        </ul>
      </div>

      <!--热门活动-->
      <div class="group activity-group" v-if="floor.length">
        <div class="group-title">热门活动</div>
        <!-- todo 隐藏掉banner -->
        <img class="topBrand" v-show="false && (addrName == '上海' || addrName == '北京')" src="http://mall.iot-tech.site/group1/M00/00/0C/wKgAgV8n2B6AfIndAANFjbxkaiw261.jpg" alt="" @click="openWebView(`/brandMall/home?brandId=${baseInfo.brandId}`, 'h5')">
        <div class="activity-wrap" v-for="(item, index) in floor" :key="index">
          <div class="activity-top">
            <image class="activity-item"
                    :src="item.banner && item.banner.advList[0] && item.banner.advList[0].advContent || ''"
                    mode="aspectFill" @click="item.banner && item.banner.type == 'brand' ?  openWebView(`/brandMall/home?brandId=${baseInfo.brandId}`, 'h5') : openWebView('/floors?pageId=' + item.pageId + '&index=' + item.index)"></image>
            <div class="angle"></div>
          </div>
          <div class="container-wrapper">
            <ul>
              <scroll-view
                class="df scroll-view-scroll"
                scroll-x="true"
                enable-flex="true"
                show-scrollbar="false"
                enhanced="true"
                @scroll="seckillScroll2"
                :style="{height: newScrollHeight*2 + 4 + 'rpx'}"
              >

              <li v-for="(items,i) in item.shopWindowProductList" :key="i" @click="openWebView(`/goods/detail?chainId=0&id=${items.id}`, 'h5')">
              <div @touchstart="scrollClick(index)">
                <div class="product-img-wrap">
                  <img :src="items.picUrl" alt="">
                  <div class="activity df-c" v-show="items.activityPriceYuan && items.activityPriceYuan < items.priceYuan">直降 {{(items.priceYuan - items.activityPriceYuan) | currency}}<span>.00</span></div>
                </div>
                <div class="">
                  <div class="product-name">{{items.productName}} {{items.spec || ''}}</div>
                  <div class="product-price" >
                    <span class="cFC1C25">￥{{items.activityPriceYuan || items.priceYuan | currency}}</span>
                  </div>
                  <div class="product-price priceYuan" v-show="items.activityPriceYuan && parseFloat(items.activityPriceYuan) < parseFloat(items.priceYuan)">
                    <span>￥{{items.priceYuan | currency}}</span>
                  </div>
                </div>
              </div>
              </li>

              </scroll-view>
              <div class="left df-l scroll-bar df br2 of">
                <div class="scroll-bar-color" :style="{width: newBarWidth[index]}"/>
              </div>
            </ul>
          </div>

        </div>
      </div>

    </div>
    <!-- 抽奖弹框 -->
    <div class="popup-wrap points-draw" v-show="drawPopupShow">
        <div class="popup-mask"></div>
        <div class="popup-body middle df-col">
          <!-- 关闭 -->
        <div class="tx-r mb5" @click.stop="closeDrawPopup">
          <img class="close" src="../assets/images/common/close_black.png" alt="">
        </div>
        <div class="draw plr12">
          <swiper
            indicator-dots="true"
            autoplay="true"
            interval="4000"
            style="height: 100%"
          >
            <swiper-item v-for="(item,index) in programWindowList" :key="index">
              <img v-if="item.href" class="draw db w100p" @click.stop="openWebView(item.href ? item.href.split('#')[1] : '', 'h5')" :src="item.imageUrl" alt="">
              <img v-else class="draw db w100p" :src="item.imageUrl" alt="">
            </swiper-item>
          </swiper>
        </div>
        </div>
    </div>
    <!-- 会员卡弹窗 todo 暂时注释掉-->
    <Popup :show="false && baseInfo.storeId && !baseInfo.cardCount && !vipCardPopupShow" :closeOnClickMask="true">
      <div class="vip-card-popup">
         <div class="top" v-if="!isWm && !isYht" >
          <div class="img-card">
            <img class="img-card" src="../assets/images/common/membership_card.png" alt="">
          </div>
          <div class="cFFF ptb10">*壹药臻选免费赠你一张会员卡</div>
        </div>
        <div v-else-if="isWm" class="top wm-vipcardBgimg">
          <div class="img-card">
            <img class="img-card" src="../assets/images/common/wanmin/membership_card.png" alt="">
          </div>
          <div class="cFFF ptb10">山西万民免费赠你一张会员卡</div>
        </div>
        <div v-else-if="isYht" class="top yht-vipcardBgimg">
          <div class="img-card">
            <img class="img-card" src="../assets/images/common/yanghetang/membership_card.png" alt="">
          </div>
          <div class="cFFF ptb10">养和堂免费赠你一张会员卡</div>
        </div>
        <div class="content">
          <div class="df df-l"> <i></i> <span class="fs15 fb mb20 tips" @click="openWebView('/user/card/cardList')">领取即享会员服务</span></div>
          <!-- <div class="df df-l"> <i></i> <span class="fs14 c666 mb10">消费200，每月获得一次闪送机会</span></div>
          <div class="df df-l"> <i></i> <span class="fs14 c666 mb10">每月只需消费3单，即可赠送一个月免运费</span> </div>
          <div class="df df-l"> <i></i> <span class="fs14 c666 mb10">大波福利，积分可兑好礼</span></div> -->

          <div class="df df-c tx-c">
            <div class="no-btn mr20" :class="[{'wm-nobtn':isWm,'yht-nobtn':isYht}]" @click="vipCardPopupShow=true">残忍拒绝</div>
            <div class="submit-btn" :class="[{'wm-btn':isWm,'yht-btn':isYht}]"  @click="openWebView('/store/new?storeId=' + baseInfo.storeId)">立即领取</div>
          </div>
        </div>
      </div>
    </Popup>
    <Popup :show="signPopupShow" :closeOnClickMask="true">
      <div class="sign-popup">
        <div class="tx-r" @click="signPopupShow=false">
          <img class="close" src="../assets/images/common/close_black.png" alt="">
        </div>
        <div class="title">
          <div class="fs24 theme-color" :class="[{'wm-color':isWm,'yht-color':isYht}]">恭喜你获得{{baseInfo.signPoints}}积分</div>
          <div class="c666 mt10 fs18">限时活动：积分抽奖得豪礼</div>
          <div class="img">
            <img src="../assets/images/common/check_in_bg.png" alt="">
          </div>
        </div>
        <div class="footer df df-c">
          <button type="primary-btn" :class="[{'wm-nobtn':isWm,'yht-nobtn':isYht}]" class=" df1 mr20" @click="openWebView('/pointsMall/dailySign')">查看积分规则</button>
          <button type="primary" :class="[{'wm-btn':isWm,'yht-btn':isYht}]" class="plr20 df1" @click="openWebView('/pointsMall/draw')">立即抽奖</button>
        </div>
      </div>
    </Popup>
    <!-- 没有引用的图片不会打包进去 -->
    <div v-show="false">
      <img src="../assets/images/home/selected_home.png" alt="">
      <img src="../assets/images/home/no_selected_home.png" alt="">
      <img src="../assets/images/home/selected_mall.png" alt="">
      <img src="../assets/images/home/no_selected_mall.png" alt="">
      <img src="../assets/images/home/selected_my.png" alt="">
      <img src="../assets/images/home/no_selected_my.png" alt="">
      <img src="../assets/images/home/selected_shopCar.png" alt="">
      <img src="../assets/images/home/no_selected_shopCar.png" alt="">
    </div>
  </div>
</template>

<style scoped lang="scss" rel="stylesheet/scss">

@keyframes fadeio {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
.df-sb{
  justify-content: space-between;
}
.cF9454E{
  color: #F9454E;
}
.right-arrow_ig {
  position: relative;
  width: 12px;
  padding-right: 20px;
  &::after {
    border: 1.5px solid #F9454E;
    content: " ";
    position: absolute;
    top: 50%;
    right: 12px;
    width: 8px;
    height: 8px;
    transform: translateY(-50%) rotate(45deg);
    border-bottom-width: 0;
    border-left-width: 0;

  }
}
.container{
  border-top:2rpx solid $themeColor;
}
.tab-search{
  height: 32px;
  background-color:#287C59;
  margin-top: -2px;
  // background:url("../assets/images/common/xcx_index_bg.png") no-repeat top center;
  background-size: 101%;
  overflow: hidden;
  .top{
    height: 32px;
    .address{
      align-items: center;
      margin-right: 14px;
      .img{
        width: 14px;
        height: 18px;
        vertical-align: middle;
        margin-left: 10px;
      }
      .right-arrow{
        width:6px;
        height:6px;
        vertical-align:middle;
        transform:rotateZ(45deg);
        border-top:4rpx solid #fff;
        border-right:4rpx solid #fff;
      }
    }
    .vip-code{
      margin-right: 10px;
      .img{
        width: 20px;
        height: 20px;
        margin: 0 auto;
      }
    }
    .search{
      position: relative;
      margin-right: 10px;
      img{
        width: 16px;
        height: 16px;
        position: absolute;
        left: 11px;
        top: 9px;
      }
      input{
        height: 32px;
        background-color: #fff;
        border-radius: 17px;
        padding-left: 34px;
      }
    }
  }
}
.main {
  .group {
    margin-bottom: 12px;
    background: #FFFFFF;
    .group-title {
      padding: 12px;
      font-size: 15px;
      font-weight: bolder;
    }

    // 我的服务
    &.service-group {
      .nav-wrap {
        display: flex;
        flex-wrap: wrap;
        padding: 18px 0 0 0;
        .nav-item {
          flex: 20% 0 0;
          padding-bottom: 18px;
          text-align: center;
          img {
            width: 44px;
            height: 44px;
          }
        }
      }
    }

    // 限时抢购
    &.activityModule{
      position: relative;
      .title-time{
        height: 18px;
        line-height: 18px;
        border: 1px solid #E55454;
        text-align: center;
        border-radius: 18px;
        overflow: hidden;
        .field {
          background-color: #E55454;
          padding: 0 4px 0 6px;
          text-align: center;
        }
        .time {
          padding: 0 6px 0 4px;
          color: #E55454;
          background-color: #ffffff;
        }
      }
      .seckill{
        .seckill-scroll-item{
          min-width: 78px;
          width: 78px;
          max-width: 78px;
          margin-right: 12px;
          &:last-child {
            margin-right: 0;
          }
          .seckill-productName{
            margin-top: 4px;
            /* height: 26px; */
            line-height: 13px;
            overflow: hidden;
          }
          .seckill-img {
            max-width: 78px;
            width: 78px;
            max-height: 78px;
            height: 78px;
            display: block;
            background: #fff;
            -webkit-background-size: 100%;
            background-size: 100%;
            img{
              width: 100%;
              height: 100%;
              display: block;
            }
          }
          .seckill-scale{
            position: relative;
            width: 100%;
            height: 9px;
            overflow: hidden;
            background: #FFF1E2;
            .scale-line{
              height: 100%;
              background: #FF543E;
              font-size: 7px;
              .scale-con{
                position: absolute;
                top: 0;
                bottom: 0;
                line-height: 9px;
                /* left: 0.6rem; */
                padding: 0 6px;
              }
            }
          }
          .seckill-price {
            line-height: 12px;
          }
        }
      }
      .more{
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
      .activity {
        width: calc(100% - 24px);
        background-color: #fff;
        display: flex;
        flex-wrap: wrap;
        padding: 0 12px 12px 12px;
        .activity-item{
          width: calc(50% - 2.5px);
          height: 55px;
          box-sizing: border-box;
          background-color: #fafafa;
          background-image: linear-gradient(-180deg, #fdfdfd 0%, #f8f8f8 100%);
          border-radius: 4px;
          overflow: hidden;
        }
        .activity-item:nth-child(1){
          margin-top: 12px;
          margin-right: 4px;
        }
        .activity-item:nth-child(2){
          margin-top: 12px;
        }
        .activity-item:nth-child(3){
          margin-top: 6px;
          margin-right: 4px;
        }
        .activity-item:nth-child(4){
          margin-top: 6px;
        }
      }
    }

    // 热门活动
    &.activity-group {
        .topBrand{
          width:100%;
          height:97px;
          padding: 0 12px;
          box-sizing: border-box;
          margin-bottom:10px;
        }
        .activity-wrap {
          position: relative;
          padding: 0 12px;
          .activity-top{
            position: relative;
            margin-bottom: 12px;
          }
          .activity-item {
            height: 97px;
            width: 100%;
            border-radius: 3px;
            vertical-align: middle;
          }
          .angle{
            position:absolute;
            width: 0;
            height: 0;
            border-width: 0 6px 8px;
            left:30px;
            bottom:0;
            border-style: solid;
            border-color: transparent transparent #fff;
          }
          .container-wrapper{
            // overflow: hidden
          }
          ul{
            overflow-x: scroll;
            white-space: nowrap;
            width:100%;
            margin-bottom:15px;
            height: 145px;
            overflow: hidden;
            border-bottom: 1px solid #EEE;
            li:nth-child(1){
              border-left:1px solid  #EEE;
            }
            li{
              width:33%;
              min-width:33%;
              height:100%;
              display: inline-block;
              // margin-right:4%;
              border-right:1px solid #EEE;
              border-top:1px solid #EEE;
              border-bottom:2px solid #EEE;
              padding-bottom:6px;
              .product-img-wrap {
                width: 100%;
                position: relative;
                display:flex;
                align-items:center;
                justify-content: center;
                img {
                  width:75%;
                  min-width:75%;
                  height:80px;
                  margin: 0 auto;
                  margin-top:5px;
                }
                .activity{
                  position: absolute;
                  top: 0;
                  right: 0;
                  padding: 0 10px  0 10px ;
                  height: 15px;
                  color: #FFFFFF;
                  font-size: 12px;
                  background-image: linear-gradient(-269deg, #F9454E 0%, #FF851D 100%);
                  border-radius: 0 0 0 5px;
                }
              }
              .product-name, .product-price {
                width: 95%;
                text-align: center;
                white-space:nowrap;
                overflow:hidden;
                text-overflow:ellipsis;
                color: #666;
                margin-top:2px;
                font-size:14px;
              }
              .cFC1C25{
                color: #FC1C25;
                font-size:14px;
              }
              .priceYuan{
                text-decoration: line-through;
                color:#808080;
                font-size: 14px;
              }
            }
          }
        }
        .scroll-view{
          position: relative;
          margin-bottom: 6px;
          &::-webkit-scrollbar {
            display:none;
            width:0;
            height:0;
            color:transparent;
          }
          .scroll-view-box{
            margin: 0 12px;
            width: calc(100% - 24px);
            overflow: hidden;
          }
          .scroll-bar{
            position: absolute;
            height: 2px;
            width: 40px;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            background: #E8E8E8;
            .scroll-bar-color{
              height: 100%;
              background: #287C59;
            }
          }
        }
        .scroll-view-scroll{
          height: 150px;
          white-space: nowrap;
          // border:1px solid green;
          &::-webkit-scrollbar {
            display:none;
            width:0;
            height:0;
            color:transparent;
          }
        }
        .scroll-bar{
          position: absolute;
          height: 2px;
          width: 40px;
          bottom: -10px;
          left: 50%;
          transform: translateX(-50%);
          background: #E8E8E8;
          .scroll-bar-color{
            height: 100%;
            background: #287C59;
          }
        }
      }
    //健康管家
    &.health-group{
        .df-row{
          display: flex;
          flex-direction: row;
        }
        ul{
          padding:0 12px;
        }
        li{
          width:32%;
          height:55px;
          margin-bottom:15px;
          img{
            width:100%;
            height:100%;
          }
        }
        li:nth-child(1), li:nth-child(2){
          margin-right:2%;
        }
      }
  }
}
.sign-popup {
  width: 270px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  text-align: center;
  overflow: hidden;
  .close{
    width: 28px;
    height: 28px;
    // float: right;
  }
  .title {
    padding-bottom: 18px;
    img{
      width: 210px;
      height: 150px;
    }
  }
}
.vip-card-popup{
  .top{
    width: 320px;
    height: 180px;
    background: url("../assets/images/common/membership_card_bg.png") no-repeat center;
    background-size: 100% 100%;
    padding:50px 12px 0 12px;
    box-sizing: border-box;
  }
  .img-card{
    width: 160px;
    height: 86px;
    margin: 0 auto;
  }
  .content{
    width: 320px;
    height: 120px;
    background-color: #fff;
    border-radius: 0 0 6px 6px;
    box-sizing: border-box;
    i{
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background-color: #EEE;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }
  .tips{
    margin-top: 20px;
  }
  .no-btn{
      border: 1px solid $themeColor;
      width: 130px;
      height: 44px;
      line-height: 44px;
      border-radius: 6px;
      color: $themeColor;
    }
    .submit-btn{
      border: 1px solid $themeColor;
      width: 130px;
      height: 44px;
      line-height: 44px;
      border-radius: 6px;
      color: #fff;
      background-color: $themeColor;
    }
}
.popup-wrap {
    .popup-mask {
      position: fixed;
      top: 0;
      left: 0;
      height: 100vh;
      width: 100%;
      background: rgba(0,0,0,0.30);
    }
    .popup-body {
      position: fixed;
      &.middle {
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
}
.points-draw{
  .middle{
    width: 320px;
  }
  .draw{
    height: 470px;
  }
  .close{
    width: 28px;
    height: 28px;
    // float: right;
  }
}

//万民主题色 #f39700
.wm-container{
  border-top:2rpx solid #f39700;
}
.wm-color{
  color:#f39700;
}
.wm-tabBgimg{
  background:url("../assets/images/common/wanmin/xcx_index_bg.png") no-repeat center;
}
.wm-vipcodeImg{
  background:url("../assets/images/common/wanmin/home_vip.png") !important;
  background-size: cover !important;
}
.wm-vipcardBgimg{
  background:url("../assets/images/common/wanmin/membership_card_bg.png") no-repeat center !important;
}
.wm-nobtn{
  border-color: #f39700 !important;
  color: #f39700 !important;
}
.wm-btn{
  border-color:#f39700 !important;
  background-color:#f39700 !important;
}

//养和堂主题色 #159547
.yht-color{
  color: #159547
}
.yht-container{
  border-top:2rpx solid #159547;
}
.yht-nobtn{
  border-color: #159547 !important;
  color: #159547 !important;
}
.yht-btn{
  border-color:#159547 !important;
  background-color:#159547 !important;
}
.yht-tabBgimg{
  background:url("../assets/images/common/yanghetang/xcx_index_bg.png") no-repeat center;
}
.yht-vipcodeImg{
  background:url("../assets/images/common/yanghetang/home_vip.png") !important;
  background-size: cover !important;
}
.yht-vipcardBgimg{
  background:url("../assets/images/common/yanghetang/membership_card_bg.png") no-repeat center !important;
}
</style>

<script>
  import {mapGetters, mapActions} from 'vuex'
  import goShare from '@/mixins/goShare'
  import Popup from '@/components/common/Popup.vue'
  import ScrollBar from '@/components/common/ScrollBar.vue';
  import env from '@/js/env.js';

  export default {
    mixins: [goShare],
    data() {
      return {
        options: {},
        baseInfo: {},
        floor: [],          //  楼层
        cancelObj: {},
        // pointsGoods: [],    //  积分商品
        // couponsList: [],    //  展示出来的优惠券
        // allCouponsList: [], //  待展示出来的优惠券
        signPopupShow: false,
        vipCardPopupShow:true,
        // couponsListCancelObj: {},
        // pointsGoodsListCancelObj: {},
        loadingUserIndexFirst: true,    //  是否第一次加载用户基础信息
        // vipCard:{},
        // area:'',
        drawPopupShow:false,
        isLive:false,
        isECoin:"",
        isIntegral:"",
        // showJson: undefined,
        isWm: "",
        isYht: "",
        programWindowList: [], // 抽奖弹框的轮播图
        isWxWork: wx.getSystemInfoSync().environment === 'wxwork',    //  是否是企业微信小程序
        sharePhone:'',
        employeeType: 0,
        again:0,
        isShenYang: true,
        vichyShow: true,
        flashSale: false, // 限时抢购显隐
        myService: [],
        activityModule: [], // 活动板块
        scroll: '',
        secKillList: [], // 限时抢购的活动商品
        //  倒计时
        tabList: [
          { id: 1, name: '0:00', time: 0, },
          { id: 3, name: '8:00', time: 8, },
          { id: 4, name: "12:00", time: 12, },
          { id: 5, name: '16:00', time: 16, },
          { id: 6, name: '20:00', time: 20, },
        ],
        downTimeInterval: '',
        hours: '',
        minutes: '',
        seconds: '',
        currentTime: '',
        newBarWidth: [],
        newScrollHeight: 150,
        scrollIndex:0
      }
    },

    components: {
      Popup,
      ScrollBar,
    },
    computed: {
      ...mapGetters(['location', 'scopeId', 'storeId', 'storeName', 'locationCopy', 'wxID', 'nearestChain', 'userInfo', 'sharePageUrl', 'shareUrl', 'openId', 'cardDepartId','locationDetailInfo','addrName','showIndexPopup']),
      store () {
        return this.nearestChain
      },
      showMain () {     //  是否显示界面
        if (this.scopeId && this.openId) {
          return true
        }
        return false
      },
      phone () {
        if (this.userInfo && this.userInfo.phone) {
          this.updateAppSetting({
            userPhone:this.userInfo.phone
          })
          return this.$utils.secretMobile(this.userInfo.phone)
        }
        return ''
      },
    },

    watch: {
      'baseInfo.cardCount'(newVal, oldVal){
        this.vipCardPopupShow = this.baseInfo.cardCount?true:false
      },
      locationCopy (newVal, oldVal) {
        this.getUserIndex()
        console.log('locationCopy 的 newVal,oldVal：', newVal,oldVal)
        if (newVal && oldVal != newVal) {
          this.getHomePage();
          this.login().then(data => {
            this.goShareCondition('index')
            this.getVipCardList()
          }, err => {})
        }
      },
      userInfo (newVal, oldVal) {
        if (newVal && !oldVal) {    //  getUserIndex会更新 userInfo， 因为查看会员码用到userNo
          this.getUserIndex()
          this.isShenyangCity()
          console.log('拿取地理位置');
        }
      },
      addrName(){
        this.getUserIndex();
        // this.getHomePage();
      },
      'baseInfo.storeId'(){
         wx.setStorageSync('isWm','false');
         this.isWm = false;
         wx.setStorageSync('isYht','false');
         this.isYht = false;
        if(this.baseInfo.storeId=='4767'){ //万民：4767
          wx.setNavigationBarColor({
            backgroundColor:'#f39700',
            frontColor:'#ffffff'
          });
          wx.setNavigationBarTitle({
            title: '山西万民',
          });
          wx.setBackgroundColor({
            backgroundColor: '#f39700'
          });
           wx.setStorageSync('isWm','true')
           this.isWm = true;
        }
         if(this.baseInfo.storeId=='4776'){ //养和堂：4776
           wx.setNavigationBarColor({
             backgroundColor:'#159547',
             frontColor:'#ffffff'
           });
           wx.setNavigationBarTitle({
             title: '养和堂',
           });
           wx.setBackgroundColor({
             backgroundColor: '#159547'
           });
            wx.setStorageSync('isYht','true')
            this.isYht = true;
         }
          if(this.baseInfo.storeId!='4776' && this.baseInfo.storeId!='4767'){
            wx.setNavigationBarColor({
              backgroundColor:'#287C59',
              frontColor:'#ffffff'
            });
            wx.setNavigationBarTitle({
              title: '壹药臻选',
            });
            wx.setBackgroundColor({
              backgroundColor: '#287C59'
            })
          }
         console.log("isWm is "+this.isWm);
         console.log("isYht is " + this.isYht)
      },
    },

    methods: {
      ...mapActions(['updateAppSetting', 'loadShareUrl', 'login', 'openRouteByWebview', 'openLiveByWebview', 'openHealthRouteByWebview', 'openBrandByWebview']),
      dev () {
        wx.showToast({
          title: '开发中，敬请期待！',
          icon: 'none',
          duration: 2000
        })
      },
      seckillScroll2(e) {
        // console.log('seckillScroll2', e)
        const scrollLeft = e.target.scrollLeft;
        const scrollWidth = e.target.scrollWidth; // 可滚动的距离
        const windowWidth = wx.getSystemInfoSync().windowWidth;
        this.newBarWidth[this.scrollIndex] = (scrollLeft/(scrollWidth - windowWidth - 26 )) * 40 + 'px';
      },
      scrollClick(i){
        this.scrollIndex = i
      },
      /**
       * 前往webview
       * @param route：路径
       * @param type：类型 healthWX健康社区 page原生页面 mall商城
       */
      openWebView (route, type = 'mall') {
        console.log('openWebView route：', route, type);
        // 原来有的逻辑
        if(this.drawPopupShow){
          this.drawPopupShow = false
          this.updateAppSetting({
            showIndexPopup:1
          })
        }
        // 获取区域公司
        let companyStr = this.$const.getAreaCompany(this.baseInfo.storeId)
        let routeArr = {
          '/index':'送药上门', // 健康社区&送药上门
          [`/brandMall/home?brandId=${this.baseInfo.brandId}`]: '薇姿品牌馆',
          '/goods/searchHome':'实时找药',
          '/chat/room':'用药咨询',
          '/chronic':'慢病管理',
          '/user/card/cardList':'卡包',
          '/pages/nearbyStore/list':'附近门店',
          '/pointsMall':'积分商城',
          '/pointsMall/draw':'积分抽奖',
          '/user/order/consumptionList':'消费记录',
          '/my/memberList':'健康档案',
          '/goods/drugDemandList': '我的需求',
          // 特病管理 目前无用
          '/specialDisease':'特病管理',
          // 直播活动没有地址
        }
        if(type == 'healthWX'){
          routeArr['/index']='健康社区'
        }else{
          routeArr['/index']='送药上门'
        }
        // 友盟埋点
        // this.$uma.trackEvent('serviceItem', {
        //   'name': routeArr[route],
        //   'chainName':this.nearestChain.chainName ||'',
        //   'chainId':this.nearestChain.id || '',
        //   'storeId':this.storeId,
        //   'storeName':this.storeName
        // })
        if (!this.scopeId || !this.openId) {
          return
        }
        if((type=='dzb' || type=='healthWX') && this.baseInfo.storeId && !this.baseInfo.cardCount){
            wx.showToast({
            title: '请先领取会员卡',
            icon: 'none',
            duration: 2000
          })
          return
        }
        if (!this.userInfo) {
          this.goLoginAction()
          return
        }
        if ((['/pointsMall'].includes(route) && this.baseInfo.integralFlag != 1) || (['/index'].includes(route) && this.baseInfo.medicineToDoorflag != 1 && type == 'h5')) {
          // console.log(this.cardDepartId,'pointsMall')
          wx.showToast({
            title: '此功能该区域正在建设中！',
            icon: 'none',
            duration: 2000
          })
          return
        }

        // type == h5, 跳转h5的页面
        if (type == 'h5') {
          this.openRouteByWebview({
            route: route,
            jumpType: 'push',
            sendLocation: true
          })
          return;
        }
        // type == brands, 跳转h5的品牌馆
        if (type == 'brands') {
          if (!this.baseInfo.brandId) {
            wx.showToast({
              title: '此功能该区域正在建设中！',
              icon: 'none',
              duration: 2000
            })
          } else {
            route = `/brandMall/home?brandId=${this.baseInfo.brandId}`
            this.openRouteByWebview({
              route: route,
              jumpType: 'push',
              sendLocation: true
            })
          }
          return;
        }
        // type == page, 原生页面
        if (type == 'page') {
          mpvue.navigateTo({
            url: route
          });
          return;
        }
        // type == more, 跳转tab页面
        if (type == 'more') {
          // 切换到导航栏页面
          wx.switchTab({
            url: route
          })
          return;
        }
        // type == healthWX, 健康社区
        if (type == 'healthWX') {
          if (!this.cardDepartId) {
            wx.showToast({
              title: '此功能该区域正在建设中！',
              icon: 'none',
              duration: 2000
            })
          } else {
            this.openHealthRouteByWebview({
              route: route,
              jumpType: 'push'
            })
          }
          return;
        }
        // type == live, 直播外链
        if(type == 'live'){
          wx.navigateToMiniProgram({
            appId: 'wx92d650b253f8f2e3',//小程序appid
            path: 'pages/index/index?zbid=1106745572',//跳转关联小程序app.json配置里面的地址
            extraData: {//需要传递给目标小程序的数据，目标小程序可在 App.onLaunch()，App.onShow() 中获取到这份数据。
              // zbid: '1106745572'
            },
          //**重点**要打开的小程序版本，有效值 develop（开发版），trial（体验版），release（正式版）
            envVersion: 'release',
            success(res) {
              // 打开成功
            }
          })
          return
        }
        if (type == 'mall' || !type) {
          this.openRouteByWebview({
            route: route,
            jumpType: 'push',
            sendLocation: true
          })
        }
      },
      jumpWebView(route){
        if(!route) return;
        mpvue.navigateTo({
          url: `/pages/webview?route=${encodeURIComponent(route)}`
        })
      },
      jumpWeizan () {
        wx.navigateToMiniProgram({
          appId: 'wx92d650b253f8f2e3',//小程序appid
          path: 'pages/index/index?zbid=1106745572',//跳转关联小程序app.json配置里面的地址
          extraData: {//需要传递给目标小程序的数据，目标小程序可在 App.onLaunch()，App.onShow() 中获取到这份数据。
            // zbid: '1106745572'
          },
        //**重点**要打开的小程序版本，有效值 develop（开发版），trial（体验版），release（正式版）
          envVersion: 'release',
          success(res) {
            // 打开成功
          }
        })
      },
      // 前往登录
      goLoginAction () {
        wx.navigateTo({
          url: '/pages/register'
        })
      },
      getMyServices(list) {
        if (!list.length) {
          list = [
            {name: '送药上门', nameEn: 'h5_index', isShow: 1},
            {name: '薇姿品牌馆', nameEn: 'brand_vichy', isShow: 1},
            {name: '实时找药', nameEn: 'search_medicine', isShow: 1},
            {name: '直播活动', nameEn: 'live', isShow: 1},
            {name: '健康社区', nameEn: 'healthy_community', isShow: 1},
            {name: '慢病管理', nameEn: 'slow_disease', isShow: 1},
            {name: '用药咨询', nameEn: 'online_consulting', isShow: 1},
            {name: '附近门店', nameEn: 'nearby_stores', isShow: 1},
            {name: '积分商城', nameEn: 'integral_mall', isShow: 1},
            {name: '积分抽奖', nameEn: 'integral_lottery', isShow: 1},
            {name: '消费记录', nameEn: 'records_consumption', isShow: 1},
            {name: '卡包', nameEn: 'card_package', isShow: 1},
            {name: '健康档案', nameEn: 'health_management', isShow: 1},
            {name: '我的需求', nameEn: 'my_need', isShow: 1},
          ]
        }
        this.myService = [...list];
        return;
        const myServiceObj = {
          'h5_index': {imgSrc: require('../assets/images/home/home_mall.png'), url: '/index', type: 'h5'},
          'brand_vichy': {imgSrc: require('../assets/images/home/hoem_brand_vichy.png'), url: `/brandMall/home?brandId=${this.baseInfo.brandId}`, type: 'brands'},
          'search_medicine': {imgSrc: require('../assets/images/home/home_search_medicine.png'), url: '/goods/searchHome', type: 'h5'},
          'online_consulting': {imgSrc: require('../assets/images/home/home_online_consulting.png'), url: '/chat/room', type: ''},
          'healthy_community': {imgSrc: require('../assets/images/home/home_healthy_community.png'), url: '/index', type: 'healthWX'},
          'slow_disease': {imgSrc: require('../assets/images/home/home_slow_disease_management.png'), url: '/chronic', type: 'healthWX'},
          'live': {imgSrc: require('../assets/images/home/home_live.png'), url: '', type: 'live'},
          'card_package': {imgSrc: require('../assets/images/home/home_card_package.png'), url: '/user/card/cardList', type: ''},
          'nearby_stores': {imgSrc: require('../assets/images/home/home_nearby_stores.png'), url: '/pages/nearbyStore/list', type: 'page'},
          'integral_mall': {imgSrc: require('../assets/images/home/home_integral_mall.png'), url: '/pointsMall', type: 'h5'},
          'integral_lottery': {imgSrc: require('../assets/images/home/home_integral_lottery.png'), url: '/pointsMall/draw', type: 'h5'},
          'records_consumption': {imgSrc: require('../assets/images/home/home_records_consumption.png'), url: '/user/order/consumptionList', type: ''},
          'health_management': {imgSrc: require('../assets/images/home/home_health_management.png'), url: '/my/memberList', type: 'healthWX'},
          'my_need': {imgSrc: require('../assets/images/home/home_my_need.png'), url: '/goods/drugDemandList', type: 'h5'},
        }
        const myService = [];
        list.forEach(v => {
          if (v.isShow == 1) {
            v.imgSrc = myServiceObj[v.nameEn].imgSrc;
            v.url = myServiceObj[v.nameEn].url;
            v.type = myServiceObj[v.nameEn].type;
            myService.push(v);
          }
        });
        myService.push({name: '更多', type: 15, imgSrc: require('../assets/images/home/home_more.png'), url: '/pages/user', type: 'more'});

        this.myService = myService;
      },
      getHomePage () {
        //  获取楼层
        this.getDownTime();
        this.getShopCarNum();
        this.secKillList = [];
        this.myService = [];
        this.activityModule = [];
        this.$api.getHomePage({
          scopeId: this.scopeId,
          storeId: this.storeId
        }).then(data => {
          const brandFloor = {
            banner: {
              advList: [{
                advContent: 'http://mall.iot-tech.site/group1/M00/00/0C/wKgAgV8n2B6AfIndAANFjbxkaiw261.jpg'
              }],
              type: 'brand'
            }
          }
          this.floor = data.floor || []
          if (this.addrName == '上海') {
            // this.floor.unshift(brandFloor)
          }
          console.log('getMyServices------------------', data)
          this.getMyServices(data.channel || []);
          this.getActivityModule(data.activityModule || []);
          this.getSecKill(data.promotion || []);
        }, err => {
          console.log('楼层获取失败', err)
        })
        this.isShenyangCity();
      },
      getUserIndex (a= 0) {
        // 切换地址前先隐藏弹窗
        if (!this.userInfo) {
          return
        }

        if (this.loadingUserIndexFirst) {
          wx.showLoading()
        }

        //  获取用户基本信息
        this.cancelObj.request && this.cancelObj.request.abort()
        // console.log(a)
        this.$api.userInfoIndex(this.cancelObj).then(data => {
          if (this.loadingUserIndexFirst) {
            wx.hideLoading()
          }
          this.vipCardPopupShow = true
          this.baseInfo = data || {}
          //品牌馆是否显示
          if(!this.baseInfo.brandId){
            this.vichyShow = false
          }else{
            this.vichyShow = true
          }

          // 首页抽奖弹窗判断
          if (!this.programWindowList.length) {
            this.getProgramWindow();
          }

          this.updateAppSetting({
            cardDepartId: this.baseInfo.cardDepartId || '',
            userInfo: this.baseInfo.userInfo
          })
          this.loadingUserIndexFirst = false
          this.isECoin = this.baseInfo.isECoin
          this.isIntegral = this.baseInfo.isIntegral


        }, err => {
          if (this.loadingUserIndexFirst) {
            wx.hideLoading()
          }

          err.msg && wx.showModal({
            title: '基本信息获取提示',
            content: err.msg,
            success: (res) => {}
          })
        })
      },
      getSecKill(secKillList) {
        this.secKillList = secKillList;
      },
      getActivityModule(activityModule) {
        // 判断限时秒杀(flashSale)、预售专场(preSale)、领优惠券(coupons)、超值拼团(groupBuy)、组合套餐(package)的显隐
        if (!activityModule.length) {
          activityModule = [
            {nameEn: 'flashSale', isShow: 1},
            {nameEn: 'preSale', isShow: 1},
            {nameEn: 'coupons', isShow: 1},
            {nameEn: 'groupBuy', isShow: 1},
            {nameEn: 'package', isShow: 1},
          ];
        }
        const activityModuleArr = [];
        const imgSrcObj = {
          'preSale': {imgSrc: require('../assets/images/home/activity_preSale.png'), goUrl: '/activity/preSale'},
          'coupons': {imgSrc: require('../assets/images/home/activity_coupons.png'), goUrl: '/activity/coupons'},
          'groupBuy': {imgSrc: require('../assets/images/home/activity_group.png'), goUrl: '/activity/collage'},
          'package': {imgSrc: require('../assets/images/home/activity_package.png'), goUrl: '/activity/package'},
        };
        activityModule.forEach((v) => {
          if (v.nameEn == 'flashSale') {
            if (v.isShow == 1) {
              this.flashSale = true;
            }
          } else {
            if (v.isShow == 1) {
              v.imgSrc = imgSrcObj[v.nameEn].imgSrc;
              v.goUrl = imgSrcObj[v.nameEn].goUrl;
              activityModuleArr.push(v);
            }
          }
        })
        // 不是双数就 -1 凑成双数
        if (activityModuleArr.length % 2 == 1) {
          activityModuleArr.length = activityModuleArr.length - 1;
        }
        this.activityModule = activityModuleArr;
      },
      // 获取购物车角标数字
      getShopCarNum() {
        this.$api.getShopCarNum().then(data => {
          if (data) {
            console.log('购物车数量：', data)
            wx.setTabBarBadge({
              index: 2,
              text: `${data}`,
            })
          }
        }, err => {})
      },
      //  活动倒计时
      getDownTime() {
        let currentHours = new Date().getHours();
        for (let i = 0; i < this.tabList.length; i++) {
          let time1 = this.tabList[i].time
          let time2 = this.tabList[i + 1] && this.tabList[i + 1].time
          if ((!time2 || currentHours < time2) && currentHours >= time1) {
            this.currentIndex = i
            this.currentTime = this.tabList[i].time;
          }
        }

        if (this.downTimeInterval) {
          clearInterval(this.downTimeInterval)
        }
        let end;
        if (this.currentIndex == 0) {
          end = new Date(this.time(8)).getTime()
        } else {
          end = new Date(this.time(4)).getTime()
        }

        this.downTimeInterval = setInterval(() => {
          let currentTime = new Date().getTime();
          if (currentTime > end) {
            return
          }
          let distance = end - currentTime;

          this.hours = Math.floor(distance / (1000 * 60 * 60))
          this.minutes = Math.floor(distance / 1000 / 60 % 60)
          this.seconds = Math.floor(distance / 1000 % 60)
        }, 1000)
      },
      // 时间处理
      time(distance = 0) {
        let currentTime = this.currentTime * 1 + distance
        if (currentTime < 10) {
          currentTime = "0" + currentTime
        }
        const ymd = new Date().toLocaleDateString();
        const hms = `${currentTime}:00:00`

        return `${ymd} ${hms}`
      },
      // 获取首页抽奖轮播弹框
      getProgramWindow () {
        const params = {
          storeId: this.baseInfo.storeId,
        }
        this.$api.getProgramWindow(params).then(data => {
          this.programWindowList = data.programWindowCode;
          if (this.programWindowList.length) {
            this.drawPopupShow = true;
          } else {
            this.drawPopupShow = false;
          }
        }, err => { console.log(err) })
      },
      // 更换位置
      replaceAddress() {
        let _this = this
        console.log('打开地图')

        wx.chooseLocation({
          success: res => {
            this.checkShowAddress = false
            wx.showLoading({
              title: '登录中'
            })
            console.log('this.location.latitude: ',this.location.latitude,1)
            this.updateAppSetting({
              location: { latitude: res.latitude, longitude: res.longitude },
              locationDetailInfo: res,
              addrName:this.$const.getAreaStr(res.address),
            });
            // setTimeout(()=>{
            //   wx.hideLoading()
            // },1500)

            //沈阳市页面坑位显示与否
            let reg = /.+?(省|市|自治区|自治州|县|区)/g;
            let city = res.address.match(reg)
            if(city[1] == '沈阳市'){
              this.isShenYang = false
            }else{
              this.isShenYang = true
            }
          }
        });
      },
      // 关闭
      closeDrawPopup(){
        this.drawPopupShow = false
          this.updateAppSetting({
            showIndexPopup:1
          })
      },
      getIsLive(){
      var that = this
      wx.request({
        url: env.apiBaseUrl + '/qvb.json',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success (res) {
          that.isLive = res.data.qlvb
        }
      })
    },
      getWxWork(){
        if(this.isWxWork){
        let that = this
          wx.qy.login({
            success: function(res) {
              console.log('企业微信code: ', res.code)
              if (res.code) {
                // 1.企业微信code换取手机号
                // 2.分享拼接企业微信code与渠道
                that.$api.getUserInfoByCode({
                  code: res.code
                }).then(data => {
                  that.sharePhone = data.mobile
                  that.employeeType = 1
                  that.updateAppSetting({
                    sharePhone: data.mobile,
                    employeeType: 1
                  })
                  if(res.data.code != 1 && that.again == 0 || that.again == 1){
                    that.again ++
                    that.getWxWork();
                  }
                }, err => {
                  if(that.again == 0 || that.again == 1){
                    that.again ++
                    that.getWxWork();
                  }
                })
              }
            }
          });
        }else{
          this.updateAppSetting({
            employeeType: 0
          })
        }
      },
      getShare(){
        //获取分享人手机号与渠道
        console.log(this.options,"index页获取渠道")
        if (this.options.userPhone) {
          this.updateAppSetting({
            getUserSharePhone: this.options.userPhone,
            getEmployeeType: this.options.employeeType
          })
          let params = {
            phone :this.options.userPhone || "",
            employeeType: this.options.employeeType|| ""
          }
          this.$api.bindEmployee(params).then(data => {
          }, err => {})
        }
      },
      isShenyangCity(){
        let reg = /.+?(省|市|自治区|自治州|县|区)/g;
        if(this.locationDetailInfo && this.locationDetailInfo.address){
          let city = this.locationDetailInfo.address.match(reg)

          if(city[1] == '沈阳市'){
            this.isShenYang = false
          }else{
            this.isShenYang = true
          }
        }
      },

    },
    onLoad(options) {
      this.options = options
      this.updateAppSetting({
        indexOptions: options
      })

      this.loadShareUrl()
      this.getWxWork();
      //  每次重启首页都要重新登录
      if (this.scopeId) {
        this.getHomePage();
        this.login().then(data => {
          this.goShareCondition('index')
        }, err => {});
      }
      this.getShare();
    },
    onShow () {

      // this.getUserIndex()
      this.getIsLive();
      this.newBarWidth=[]
    },
    onHide () {
      this.cancelObj.request && this.cancelObj.request.abort()
    },
    //  转发设置
    onShareAppMessage() {
      let phone = this.sharePhone || this.userInfo.phone || ''
      console.log(this.sharePhone, this.employeeType, '首页转发企业渠道')
      console.log(this.userInfo.phone, this.employeeType, '首页转发普通渠道')
      return {
        title: '壹药臻选',
        desc: '',
        path: 'pages/index?userPhone=' + phone +'&employeeType=' + this.employeeType,
        success: () => {},
      }
    },
}
</script>

